//
//  HJMyDynamicVC.m
//  project
//
//  Created by yefei on 2019/7/24.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJMyDynamicVC.h"
#import "YFMineViewModel.h"
#import "YFMyDongtaiCell.h"
#import "YFAlert.h"
#import "HJOtherDynamic.h"
#import "HJAlertView.h"
#import "LEEAlert.h"
#import "YFCamera.h"
#import "YFImagePicker.h"
#import "TZImageManager.h"
#import "HJAddVC.h"
#import "HJNavigationViewController.h"
@interface HJMyDynamicVC ()<TZImagePickerControllerDelegate>
@property (nonatomic, strong) YFMineViewModel *viewModel;
/**
 点击index
 */
@property (nonatomic,strong) NSIndexPath  * indexpath;
@end

@implementation HJMyDynamicVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"我的动态";
    self.rightNavImageName = @"chat_add_normal";
    // 开始刷新加载
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark -- 发布动态
-(void)didClickRightNavAction {
    @weakify(self)
    [LEEAlert actionsheet].config
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        @strongify(self)
        action.title = @"拍摄";
        action.titleColor = [UIColor darkGrayColor];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:18];
        
        action.clickBlock = ^{
            YFCamera *camera = [YFCamera camera];
            camera.isTakePhoto = NO;
            [camera show];
            camera.maxSeconds = 15;
            @weakify(self)
            [camera completedWithImage:^(UIImage * _Nullable image) {
                @strongify(self)
                NSMutableArray *photos = [NSMutableArray arrayWithCapacity:1];
                [photos addObject:image];
                NSMutableArray *imageDatas = [NSMutableArray arrayWithCapacity:1];
                NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
                [imageDatas addObject:imageData];
                
                HJAddVC *addVC = [HJAddVC new];
                addVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                addVC.dongtaiType = YFDongtaiTypeImages;
                addVC.photos = photos;
                addVC.imageDatas = imageDatas;
                [self.navigationController pushViewController:addVC animated:YES];
                
            } withVideo:^(UIImage * _Nullable firstFrameImage, NSURL * _Nullable videoURL, long long duration) {
                @strongify(self)
                HJAddVC *addVC = [HJAddVC new];
                addVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                addVC.dongtaiType = YFDongtaiTypeVideo;
                addVC.videoCoverImage = firstFrameImage;
                addVC.videoURL = videoURL;
                addVC.videoDuration = duration;
                [self.navigationController pushViewController:addVC animated:YES];
            }];
        };
    })
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"从手机相册选择";
        action.titleColor = [UIColor darkGrayColor];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:18];
        @strongify(self)
        action.clickBlock = ^{
            @weakify(self)
            [[TZImagePickerTool tools] selectVideoFor:self isDismiss:YES complete:^(UIImage *coverImage, NSString *filePath, long audioDurationSeconds) {
                @strongify(self)
                HJAddVC *addVC = [HJAddVC new];
                addVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                addVC.dongtaiType = YFDongtaiTypeVideo;
                addVC.videoCoverImage = coverImage;
                addVC.videoURL = [NSURL URLWithString:filePath];
                addVC.videoDuration = audioDurationSeconds;
                addVC.ispush = YES;
                HJNavigationViewController * navi = [[HJNavigationViewController alloc]initWithRootViewController:addVC];
                [self presentViewController:navi animated:YES completion:nil];
            }];
        };
    })
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.type = LEEActionTypeCancel;
        action.title = @"取消";
        action.titleColor = [UIColor grayColor];
        action.font = [UIFont fontWithName:PingFangSC_Medium size:18];
    })
    .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
    .LeeShow();
}

#pragma mark -- 初始化UI
-(void)configTableView {
    self.tableViewStyle = UITableViewStylePlain;
    [super configTableView];
    
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.showsVerticalScrollIndicator = YES;
    self.tableView.emptyView = self.tipEmptyView;
    [self.tableView registerCellByNibName:@"YFMyDongtaiCell"];
    
    @weakify(self)
    self.tableView.fullScreenRefresh(^{
        @strongify(self)
        self.page = 1;
        [self loadDataWithPage:self.page];
    })
    .loadMore(^{
        @strongify(self)
        self.page ++;
        [self loadDataWithPage:self.page];
    });
    self.indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
}
#pragma mark --ViewModel
- (YFMineViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[YFMineViewModel alloc] init];
    }
    return _viewModel;
}

- (void)loadDataWithPage:(NSInteger)page {
    BOOL isRefresh = self.tableView.mj_header.refreshing;
    @weakify(self)
    self.viewModel.loadMyDongtai(page, isRefresh, ^(BOOL isSuccess, BOOL isBottom, NSString *error){
        @strongify(self)
        [self.tableView endRefresh];
        
        if (!isSuccess) {
            if (self.viewModel.cellVMs.count == 0) {self.tipEmptyView.message = error; }
            else { [YFHud showError:error]; }
        }
        [self.tableView reloadData];
        
        if (isBottom) { [self.tableView.mj_footer endRefreshingWithNoMoreData]; }
        else { [self.tableView.mj_footer endRefreshing]; }
        
        self.tableView.mj_footer.hidden = self.viewModel.cellVMs.count == 0;
    });

}

#pragma mark -- UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.cellVMs.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.viewModel.cellVMs[indexPath.row].cellHeight;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YFMyDongtaiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YFMyDongtaiCell" forIndexPath:indexPath];
    cell.viewModel = self.viewModel.cellVMs[indexPath.row];
    
    @weakify(self)
    cell.deleteAction = ^{
        @strongify(self)
        @weakify(self)
        YFAlert.showDeleteMyDongtai(^(BOOL isDeletate){
            @strongify(self)
            if (isDeletate) {
                @weakify(self)
                YFAlert.showDeleteConfirmMyDongtai(^(BOOL confirmDelete){
                    @strongify(self)
                    if (confirmDelete) {
                        [self deleteMyDongtaiWithIndex:indexPath.row];
                    }
                });
            }
        });
    };
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJOtherDynamic * dynamicVC = [HJOtherDynamic new];
    dynamicVC.cellModel = self.viewModel.cellVMs[indexPath.row];
    self.indexpath = indexPath;
    dynamicVC.isMine = YES;// 个人界面去查看不需要点赞
    @weakify(self)
    dynamicVC.didBackBtnClicked = ^(NSString * _Nonnull zanNum, BOOL isSelecte, BOOL isMine) {
        @strongify(self)
        self.viewModel.cellVMs[self.indexpath.row].praiseAmount = zanNum;
        self.viewModel.cellVMs[self.indexpath.row].isPraise = isSelecte;
        [self.tableView reloadRowsAtIndexPaths:@[self.indexpath] withRowAnimation:UITableViewRowAnimationNone];
    };
    [self.navigationController pushViewController:dynamicVC animated:YES];
}


- (void)deleteMyDongtaiWithIndex:(NSInteger)index {
    @weakify(self)
    self.viewModel.deleteDongtai([HJUserManager getUserModel].userId, @[self.viewModel.cellVMs[index].albumId], ^(BOOL isSuccess, NSString *error) {
        @strongify(self)
        if (isSuccess) {
            NSMutableArray<YFMineCellViewModel *> *array = self.viewModel.cellVMs.mutableCopy;
            YFMineCellViewModel *vm = [array objectAtIndex:index];
            [array removeObject:vm];
            self.viewModel.cellVMs = array;
            [self.tableView reloadData];
            if (array.count==0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    HJAlertView * alertView = [HJAlertView alert];
                    alertView.content = @"发布新动态，让TA乐见你";
                    alertView.cancelTitle = @"等会儿发";
                    alertView.okTitle = @"马上发";
                    [alertView show];
                    alertView.block = ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationPublicDontai object:nil];
                    };
                    return;
                });
            }
        } else {
            [YFHud showError:error];
        }
    });
}
// 选择视频的回调
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHImageRequestOptionsVersionCurrent;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        AVURLAsset *urlAsset = (AVURLAsset *)asset;
        NSURL *videoUrl = urlAsset.URL;
        LKLog(@"%@",videoUrl.absoluteString);
        
        // 获取音频时长
        AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:videoUrl options:nil];
        CMTime audioDuration = audioAsset.duration;
        
    }];
}
@end
